package file;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import common.Singleton;
import view.Main;
import vo.Mean;

import java.io.*;
import java.util.Iterator;

public class XlsOperator {

    private Main main;

    private static XlsOperator xlsOperator;
    private XlsOperator() {}
    public static XlsOperator getOperator() {
        if(xlsOperator == null) {
            xlsOperator = new XlsOperator();
            xlsOperator.main = Singleton.main();
        }
        return xlsOperator;
    }

    /**
     * 读取Excel
     */
    public void readExcel() {
        File file = Singleton.fUtil().findFile("xlsx");
        if (file == null)
            return;
        Singleton.handler().clear(false);

        FileInputStream steam;
        XSSFWorkbook workbook = null;
        try {
            steam = new FileInputStream(file);
            workbook = new XSSFWorkbook(steam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Sheet sheet = workbook.getSheet("sheet1");
        int index = 0;
        Mean mean = null;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            boolean isMain = false, firstLoc = true;
            String text = "", attrs[] = new String[main.pointed_attrs.size()];
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                String value = cell.getStringCellValue();
                if (j == 0)
                    isMain = Integer.parseInt(value) != index;//
                else if (j == 1)
                    text = value;
                else if (j < main.pointed_attrs.size() + 2)
                    attrs[j - 2] = value;
                else if (firstLoc) {
                    if (isMain)
                        mean = new Mean(text, Integer.parseInt(value), index++);
                    else
                        mean = mean.addNext(text, Integer.parseInt(value));
                    mean.setAttribute(attrs);
                    firstLoc = false;
                } else
                    mean.addLocation(Integer.parseInt(value));
            }
            mean.setDescription();
        }
        Singleton.vc().attr_addAll();
    }

    public void writeExcel(boolean ask) {
        File out = Singleton.fUtil().getOutPutFile("xlsx", ask);
        if (out == null)
            return;
        Singleton.fUtil().setMeanTree();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        CellStyle titleStyle = workbook.createCellStyle(); // 样式对象
        titleStyle.setWrapText(true);// 指定当单元格内容显示不下时自动换行
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeight((short) 280);
        titleStyle.setFont(font);
        // 单元格合并：起始行，起始列，结束行，结束列
        // sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        // sheet.autoSizeColumn(5200);
        Row row = sheet.createRow(0);
        row.setHeight((short) 540);
        Cell cell = row.createCell(0);
        String attrNames[] = main.attrsName;

        // 设置标题
        String titles[] = new String[attrNames.length + 4];
        System.arraycopy(attrNames, 0, titles, 3, attrNames.length);
        titles[0] = "链号";
        titles[1] = "文字";
        titles[2] = "全文排序";
        titles[attrNames.length + 3] = "位置";
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(titleStyle); // 样式，居中
            sheet.setColumnWidth(i, 15 * 256);
        }
        row.setHeight((short) 400);

        CellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setWrapText(true);// 指定当单元格内容显示不下时自动换行
        contentStyle.setAlignment(HorizontalAlignment.CENTER);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font2 = workbook.createFont();
        font2.setBold(false);
        font2.setFontHeight((short) 250);
        contentStyle.setFont(font2);
        // 循环写入行数据
        Iterator<Mean> it = Singleton.handler().mainMean.iterator();
        int rowIndex = 1, index = 0;
        while (it.hasNext()) {
            index++;
            Mean mean = it.next();
            rowIndex = nextRowOfExcel(index, rowIndex, sheet, contentStyle, mean);
        }
        // 写入
        OutputStream outputStream;
        try {
            outputStream = new FileOutputStream(out);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int nextRowOfExcel(int index, int rowIndex, Sheet sheet, CellStyle style, Mean mean) {
        Row row = sheet.createRow(rowIndex);
        row.setHeight((short) 400);
        Cell cell;
        String attrs[] = mean.getAttributes();
        String cells[] = new String[attrs.length + 3];
        cells[0] = index + "";
        cells[1] = mean.getText();
        // 链号、文字
        System.arraycopy(attrs, 0, cells, 3, attrs.length);
        int i;
        for (i = 0; i < cells.length; i++) {
            cell = row.createCell(i);
            if (i == 2) {
                cell.setCellValue(mean.index_in_full_text);// 在第三列填入全文排序
            } else
                cell.setCellValue(cells[i]);
            cell.setCellStyle(style); // 样式，居中
        }
        // 写入位置
        cell = row.createCell(i++);
        int l = mean.getLocation();
        cell.setCellValue(l + "");
        cell.setCellStyle(style);

        rowIndex++;
        if (mean.haveNext())
            return nextRowOfExcel(index, rowIndex, sheet, style, mean.getNext());
        else
            return rowIndex;
    }
}
